package com.bigtotoro.shuiyincamera.video;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.StickerItem;
import com.bigtotoro.shuiyincamera.editimage.view.StickerView;
import com.bigtotoro.shuiyincamera.editimage.view.TextStickerView;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.image.SettingTextActivity;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;
import static com.bigtotoro.shuiyincamera.editimage.view.StickerItem.BUTTON_WIDTH;
import static com.bigtotoro.shuiyincamera.util.VideoUtil.VIDEO_SLIDE_IMAGE_DIR;

//视频加水印
public class VideoAddWater2Activity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "video-remove-water";
    private FrameLayout frameLayout;
    private VideoView videoView;

    private View layout_parent01,layout_parent02;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;

    private TextView tv_wenzi, tv_tupian;

    private String path = "/storage/emulated/0/dakashuiyin/video/slice/1553506380742.mp4"; // 3s
    private String out;
    private float scale;
    private float videoX, videoY;
    private ProgressDialog mProgressDialog;

    public TextStickerView mTextStickerView;//文本贴图显示View
    public StickerView mImageStickerView;//涂鸦模式画板

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_add_water2);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));
        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoAddWater2Activity.this,"video_add_watermark","视频添加水印");
        initBase();

        layout_parent01 = findViewById(R.id.layout_parent01);
        layout_parent02 = findViewById(R.id.layout_parent02);
        path = getIntent().getStringExtra("path");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        findViewById(R.id.btn_text).setOnClickListener(this);
        findViewById(R.id.btn_image).setOnClickListener(this);
        tv_wenzi = findViewById(R.id.tv_wenzi);
        tv_tupian = findViewById(R.id.tv_tupian);
        tv_wenzi.setTextColor(getResources().getColor(R.color.white));
        tv_tupian.setTextColor(getResources().getColor(R.color.white));

        mTextStickerView = (TextStickerView) findViewById(R.id.text_sticker_panel);//添加文字画布
        mImageStickerView = (StickerView) findViewById(R.id.sticker_add_image); //添加图片表情的画布


        VideoUtil.checkVideoDir();
        frameLayout = findViewById(R.id.frame);
        videoView = findViewById(R.id.video);

        videoView.setVideoURI(Uri.parse(path));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                videoWidth = mediaPlayer.getVideoWidth();
                videoHeight = mediaPlayer.getVideoHeight();
                videoDuration = mediaPlayer.getDuration();
                Log.d("main", "setOnPreparedListener duration " + videoDuration);

                videoView.start();
                mediaPlayer.setLooping(true); //循环播放

                frameWidth = frameLayout.getWidth();
                frameHeight = frameLayout.getHeight();
                Log.d(TAG, "frame" + frameWidth + ":" + frameHeight);
                Log.d(TAG, "video" + videoWidth + ":" + videoHeight);
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

                //Get VideoView's current width and height
                int videoViewWidth = videoView.getWidth();
                int videoViewHeight = videoView.getHeight();

                float xScale = (float) videoViewWidth / videoWidth;
                float yScale = (float) videoViewHeight / videoHeight;

                //For Center Crop use the Math.max to calculate the scale
                //float scale = Math.max(xScale, yScale);
                //For Center Inside use the Math.min scale.
                //I prefer Center Inside so I am using Math.min
                scale = Math.min(xScale, yScale);

                float scaledWidth = scale * videoWidth;
                float scaledHeight = scale * videoHeight;

                //Set the new size for the VideoView based on the dimensions of the video
                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = (int) scaledWidth;
                layoutParams.height = (int) scaledHeight;
                videoView.setLayoutParams(layoutParams);

                videoView.post(new Runnable() {
                    @Override
                    public void run() {
                        //文字画布父布局的宽高等于视频宽高
                        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) layout_parent01.getLayoutParams();
                        layoutParams.width = videoView.getWidth();
                        layoutParams.height = videoView.getHeight();
                        layoutParams.gravity = Gravity.CENTER;
                        layout_parent01.setLayoutParams(layoutParams);
                        //图片画布父布局的宽高等于视频宽高
                        FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) layout_parent02.getLayoutParams();
                        layoutParams2.width = videoView.getWidth();
                        layoutParams2.height = videoView.getHeight();
                        layoutParams2.gravity = Gravity.CENTER;
                        layout_parent02.setLayoutParams(layoutParams2);

                        Log.i("文字水印1", "文字水印设置后 videoView.getWidth() ===" + videoView.getWidth() + "文字水印 videoView.getHeight()===" + videoView.getHeight());
                        Log.i("文字水印1", "文字水印设置后 mTextStickerView width ===" + mTextStickerView.getWidth() + "文字水印 mTextStickerView height===" + mTextStickerView.getHeight()+"文字水印 mTextStickerView getX ===" + mTextStickerView.getX() + "文字水印 mTextStickerView getY===" + mTextStickerView.getY());
                    }
                });


                videoView.invalidate();
                videoX = (frameWidth - layoutParams.width) / 2;
                videoY = (frameHeight - layoutParams.height) / 2;

                //调整画布的大小
//                mTextStickerView.setTextStickerViewRect(new RectF(videoX, videoY, videoX+scaledWidth, videoY+scaledHeight));//背景图片尺寸，剪裁比例(1/2,1/3，默认是-1)
//                mTextStickerView.invalidate();
                mTextStickerView.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("文字水印1", "初始化 videoView.getWidth() ===" + videoView.getWidth() + "文字水印 videoView.getHeight()===" + videoView.getHeight()+ "videoX===" +videoX+ "videoY===" +videoY+ "scaledWidth===" +scaledWidth+ "scaledHeight===" +scaledHeight);
                        Log.i("文字水印1", "初始化 mTextStickerView width ===" + mTextStickerView.getWidth() + "文字水印 mTextStickerView height===" + mTextStickerView.getHeight()+"文字水印 mTextStickerView getX ===" + mTextStickerView.getX() + "文字水印 mTextStickerView getY===" + mTextStickerView.getY());
                    }
                });
//                cropView.setCropRect(new RectF(videoX, videoY, videoX+layoutParams.width, videoY+layoutParams.height));
//                cropView.setVisibility(View.VISIBLE);

                Log.d(TAG, "scaledWidth " + scaledWidth + " scaledHeight " + scaledHeight);
                Log.d(TAG, "video after set params");
                Log.d(TAG, "videoView" + videoView.getWidth() + ":" + videoView.getHeight());
                Log.d(TAG, "videoView getx " + videoView.getX() + " and getY " + videoView.getY());
            }
        });
    }

    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    public static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i("视频去水印", "去水印完成，跳转");
                Toast.makeText(VideoAddWater2Activity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setHeight(videoHeight);
                art.setWidth(videoWidth);
                art.setCreate_time(System.currentTimeMillis() + "");
                art.setPath(out);
                art.setType(1);
                art.save();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
//                FileUtil.ablumUpdate(VideoAddWater2Activity.this, art.getPath(),1);//更新相册
                Intent intent = new Intent(VideoAddWater2Activity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, out);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", videoWidth);
                intent.putExtra("height", videoHeight);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(VideoAddWater2Activity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            } else if (msg.what == MSG_CANCLE) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };


    /**
     * 从相册选择编辑图片
     */
    private void selectFromAblum() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openAblumWithPermissionsCheck();
        } else {
            openAblum();
        }
    }

    public static final int REQUEST_PERMISSON_SORAGE = 1003;
    public static final int SELECT_GALLERY_IMAGE_CODE = 1007;
    public static final int ACTION_REQUEST_EDITIMAGE = 1009;

    private void openAblum() {
        PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                .previewVideo(true).selectionMode(PictureConfig.SINGLE).videoMinSecond(1).forResult(SELECT_GALLERY_IMAGE_CODE);
//        startActivityForResult(new Intent(this, SelectPictureActivity.class),
//                SELECT_GALLERY_IMAGE_CODE);
    }

    private void openAblumWithPermissionsCheck() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSON_SORAGE);
            return;
        }
        openAblum();
    }

    private static final int REQUEST_CODE_SETTING_TEXT = 3001;
    private int visibelMode = 0;//0已显示1未显示
    private String mContent, mColor;
    int mAlpha;

    private String imagePath;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_GALLERY_IMAGE_CODE://相册返回
                    List<LocalMedia> selectlist01 = PictureSelector.obtainMultipleResult(data);
                    if (selectlist01.size() > 0) {
                        imagePath = selectlist01.get(0).getPath();
                        handleSelectFromAblum(imagePath);
                    }
                    break;
                case REQUEST_CODE_SETTING_TEXT://设置字体返回
                    mContent = data.getStringExtra("content");
                    mColor = data.getStringExtra("color");
                    mAlpha = data.getIntExtra("alpha", -1);
                    String h = Integer.toHexString(mAlpha);
                    if (h.length() < 2) { //不足两位前面补0
                        h = "0" + h;
                    }
                    mTextStickerView.setText(mContent);
                    mTextStickerView.setTextColor(Color.parseColor("#" + h + mColor));
//                    mTextStickerView.getBackground().setAlpha(Integer.valueOf(mAlpha));


                    break;
            }
        }
    }


    private void handleSelectFromAblum(String path) {
        String filepath = path;
        path = filepath;
        /**
         * 拿到图片路径后，怎么将图片加载到mStickerView画布上？
         */
        Bitmap bitmap = BitmapUtils.getSampledBitmap(path, 200, 200);
        mImageStickerView.addBitImage(bitmap);//将从相册选取的图片加载到画布上
    }

    private void initTextStickerView() { //初始化文字画布
        mTextStickerView = findViewById(R.id.text_sticker_panel);
        mTextStickerView.setVisibility(View.VISIBLE);
        mTextStickerView.setTextColor(getResources().getColor(R.color.red));
//        mTextStickerView.setIsCanRotate(1); //设置不能旋转

        mTextStickerView.post(new Runnable() {
            @Override
            public void run() {
                Log.i("文字水印1", "文字水印设置前2 videoView.getWidth() ===" + videoView.getWidth() + "文字水印 videoView.getHeight()===" + videoView.getHeight());
                Log.i("文字水印1", "文字水印设置前2 mTextStickerView width ===" + mTextStickerView.getWidth() + "文字水印 mTextStickerView height===" + mTextStickerView.getHeight()+"文字水印 mTextStickerView getX ===" + mTextStickerView.getX() + "文字水印 mTextStickerView getY===" + mTextStickerView.getY());
            }
        });


        //设置画布的宽高
    }

    private void initImageStickerView() { //初始化图片画布
        mImageStickerView = findViewById(R.id.sticker_add_image);
        mImageStickerView.setVisibility(View.VISIBLE);
//        mImageStickerView.setIsCanRotate(1);
    }

    private void save() {

        mTextStickerView.setHelpboxInvisibel(); //让旋转按钮和边框不显示
        mImageStickerView.setHelpboxInvisibel(); //让旋转按钮和边框不显示


        if (mContent != null && mContent.length() > 0) {
            float newWidth = mTextStickerView.mHelpBoxRect.width() * mTextStickerView.mScale;
            float neHeight = mTextStickerView.mHelpBoxRect.height() * mTextStickerView.mScale;
            Log.i("文字水印", "文字水印 newWidth===" + newWidth + "文字水印 neHeight===" + neHeight + "文字水印 mContent===" + mContent + ",文字水印 mColor===" + mColor + ",文字水印 mAlpha===" + mAlpha);
            Log.i("文字水印", "文字水印 中心点X===" + mTextStickerView.layout_x + ",文字水印 中心点Y===" + mTextStickerView.layout_y + ",文字水印 缩放比===" + mTextStickerView.mScale + ",文字水印 旋转角度===" + mTextStickerView.mRotateAngle);

            MyUtils.createViewBitmap(mTextStickerView, new MyUtils.BitmapCallback() {
                @Override
                public void callback(Bitmap bitmap) {
                    if (bitmap != null) {
                        //将文字部分裁剪下来
//                        imageWidth = (int) ((mTextStickerView.mHelpBoxRect.width() - BUTTON_WIDTH*2)/scale);
//                        imageHeight = (int) ((mTextStickerView.mHelpBoxRect.height() - BUTTON_WIDTH*2)/scale);
//                        trueX = (int) ((mTextStickerView.mHelpBoxRect.left-videoView.getX())/scale);
//                        trueY = (int) ((mTextStickerView.mHelpBoxRect.top-videoView.getY())/scale);
//                        //解决边界问题
//                        trueX = trueX>0?trueX:1;
//                        trueY = trueY>0?trueY:1;
//
//                        int left = (int) mTextStickerView.mHelpBoxRect.left;
//                        int top = (int) mTextStickerView.mHelpBoxRect.top;
//                        Bitmap.createBitmap(bitmap,left,top, trueX, trueY);

                        imagePath = VideoUtil.VIDEO_SLIDE_IMAGE_DIR + "/" + System.currentTimeMillis() + ".png";
                        BitmapUtils.saveBitmap(bitmap, imagePath);
                        //将bitmap作为水印添加到视频中


                    }
                }
            });
            imageWidth = (int) (mTextStickerView.getWidth() / scale);
            imageHeight = (int) (mTextStickerView.getHeight() / scale);
            Log.i("文字水印1", "save 文字水印 mTextStickerView ===" + mTextStickerView.getWidth() + "文字水印 mTextStickerView===" + mTextStickerView.getHeight());

//            trueX = (int) videoView.getX();
//            trueY = (int) videoView.getY();

            Log.i("文字水印", "文字水印 mTextStickerView ===" + mTextStickerView.getWidth() + "文字水印 mTextStickerView===" + mTextStickerView.getHeight());
            Log.i("文字水印", "文字水印 videoView ===" + videoView.getWidth() + "文字水印 videoView===" + videoView.getHeight());
            Log.i("文字水印", "文字水印 mTextStickerView getLeft ===" + mTextStickerView.getLeft() + "文字水印 mTextStickerView getTop===" + mTextStickerView.getTop() + "文字水印 mTextStickerView getX ===" + mTextStickerView.getX() + "文字水印 mTextStickerView getY===" + mTextStickerView.getY());
            Log.i("文字水印", "文字水印 videoView getX===" + videoView.getX() + "文字水印 videoView getY= ==" + videoView.getY() + "文字水印 videoView getLeft===" + videoView.getLeft() + "文字水印 videoView getTop===" + videoView.getTop());

        }else {
            LinkedHashMap<Integer, StickerItem> addItems = mImageStickerView.getBank();// 获取每层贴图数据
            MyUtils.createViewBitmap(mImageStickerView, new MyUtils.BitmapCallback() {
                @Override
                public void callback(Bitmap bitmap) {
                    if (bitmap != null) {
                        //将文字部分裁剪下来
//                        imageWidth = (int) ((mTextStickerView.mHelpBoxRect.width() - BUTTON_WIDTH*2)/scale);
//                        imageHeight = (int) ((mTextStickerView.mHelpBoxRect.height() - BUTTON_WIDTH*2)/scale);
//                        trueX = (int) ((mTextStickerView.mHelpBoxRect.left-videoView.getX())/scale);
//                        trueY = (int) ((mTextStickerView.mHelpBoxRect.top-videoView.getY())/scale);
//                        //解决边界问题
//                        trueX = trueX>0?trueX:1;
//                        trueY = trueY>0?trueY:1;
//
//                        int left = (int) mTextStickerView.mHelpBoxRect.left;
//                        int top = (int) mTextStickerView.mHelpBoxRect.top;
//                        Bitmap.createBitmap(bitmap,left,top, trueX, trueY);

                        imagePath = VideoUtil.VIDEO_SLIDE_IMAGE_DIR + "/" + System.currentTimeMillis() + ".png";
                        BitmapUtils.saveBitmap(bitmap, imagePath);
                        //将bitmap作为水印添加到视频中
                    }
                }
            });

            imageWidth = (int) (mImageStickerView.getWidth() / scale);
            imageHeight = (int) (mImageStickerView.getHeight() / scale);

//            if (addItems != null && addItems.size() > 0) {
//                for (Integer id : addItems.keySet()) {
//                    stickerItem = addItems.get(id);
//                }
//                float roatetAngle = stickerItem.roatetAngle;
//                int width = stickerItem.bitmap.getWidth();
//                int height = stickerItem.bitmap.getHeight();
//
//                Log.i("图片水印", "图片路径 imagePath===" + imagePath);
//                Log.i("图片水印", "图片水印 左===" + stickerItem.helpBox.left + ",图片水印 上===" + stickerItem.helpBox.top + ",图片水印 右===" + stickerItem.helpBox.right + ",图片水印 下===" + stickerItem.helpBox.bottom);
//                Log.i("图片水印", "图片水印 宽度===" + stickerItem.helpBox.width() + ",图片水印 高度===" + stickerItem.helpBox.height() + " ,图片水印 旋转角度===" + roatetAngle);
//
//                imageWidth = (int) ((stickerItem.helpBox.width() - BUTTON_WIDTH * 2) / scale);
//                imageHeight = (int) ((stickerItem.helpBox.height() - BUTTON_WIDTH * 2) / scale);
//                trueX = (int) ((stickerItem.helpBox.left - videoView.getX()) / scale);
//                trueY = (int) ((stickerItem.helpBox.top - videoView.getY()) / scale);
//                int trueWidth = (int) (width / scale);
//                int trueHeight = (int) (height / scale);
//                Log.d(TAG, trueX + "," + trueY + "and " + width + "x" + height);
//
//                //解决边界问题
//                trueX = trueX > 0 ? trueX : 1;
//                trueY = trueY > 0 ? trueY : 1;
//                if ((trueX + trueWidth) >= videoWidth) {
//                    trueWidth = videoWidth - trueX - 1;
//                }
//                if ((trueY + trueHeight) > videoHeight) {
//                    trueHeight = videoHeight - trueY - 1;
//                }
//
//                Integer x = (int) stickerItem.helpBox.left;
//                Integer y = (int) stickerItem.helpBox.top;
//                Log.i("图片水印", "图片水印 x===" + x + ",图片水印 y===" + y);
//            }


        }
        //添加水印后视频保存地址
        out = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp4";
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("正在处理");

        mProgressDialog.show();

        //show=1 绿色边框
        //-i 1.jpg -vf "movie=2.jpg,scale=150:183[watermask];[in][watermask] overlay=100:100[out]" -y 3.jpg
//            String cmd = String.format("-i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s:show=0 %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);


        //分别是输入路径，图片路径，输出路径
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex '[1:v]scale=30:20[logo];[0:v][logo]overlay=10:10' %s", path, imagePath, out);
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex '[1:v]scale=30:20[logo];[0:v][logo]overlay=10:10' %s", path, imagePath, out);
//        String cmd = String.format("ffmpeg -i %s -c:v libx264 -b:v 4000k -c:a copy -vf \"movie=%s,scale= 60: 30[watermark];[in][watermark] overlay=1080-50-10:1920-50-10[out] \" %s", path, imagePath, out);
//        String cmd = String.format("ffmpeg -i %s -c:v libx264 -b:v 4000k -c:a copy -vf \"drawtext=fontsize=100:fontfile=FreeSerif.ttf:text='hello world':fontcolor=green:x=20:y=20\" %s", path, imagePath, out);
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay %s", path, imagePath, out);

//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay=x=%s:y=%s:w=%s:h=%s: %s", path,imagePath, 50+"", 100+"", 60+"", 60+"", out);

//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay=W-w %s", path, imagePath, out);
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay=main_w-overlay_w:0 %s", path, imagePath, out);//右上角


//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay=0:0", path, imgOutPath, out);//右下角
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex "[1:v]scale=100:50[s];[0:v][s]overlay=%d:%d" %s", path, imagePath, trueX, trueY, out);//右下角
//        String cmd = String.format("ffmpeg -i %s -vf drawtext=fontfile=DroidSansFallback.ttf:text=\"技术是第一生产力\":x=10:y=10:fontsize=24:fontcolor=white:shadowy=2 %s", path, out);//右下角
//        String cmd = String.format("ffmpeg -i %s -vf drawtext=fontcolor=white:fontsize=40:text=%s:x=0:y=100:fontsize=24:fontcolor=yellow:shadowy=2 %s", path, mContent, out);//右下角
//        String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s: %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);

        //文字水印
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex overlay=main_w-overlay_w:main_h-overlay_h %s", path, imgOutPath, out);//右下角
        //图片水印
        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex [1:v]scale=%d:%d[s];[0:v][s]overlay=%d:%d -preset superfast %s", path, imagePath, imageWidth, imageHeight, trueX, trueY, out);//右下角
//        String cmd = String.format("ffmpeg -y -i %s -i %s -filter_complex [1:v]scale=%d:%d[s];[0:v][s]overlay=%d:%d %s", path, imagePath,imageWidth,imageHeight, trueX, trueY, out);//右下角
        int duration = VideoUtil.getDuration(this, path);
        Log.d(TAG, "duration " + duration);
        Log.d(TAG, "cmd " + cmd);

        String[] commands = cmd.split(" ");
        try {
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i("去水印保存", "EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i("去水印保存", "EpEditor.execCmd onProgress");
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);

                }

                @Override
                public void onCancel() {
                    Log.i("去水印保存", "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i("去水印保存", "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private StickerItem stickerItem;

    private int trueX, trueY;
    private int imageWidth, imageHeight;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_save: //调用视频加水印方法，获取画布上的文字和图片位置

                //添加友盟事件统计
                MyUtils.addUmengEvent(VideoAddWater2Activity.this,"video_add_watermark_save","视频添加水印保存");
                save();

                break;
            case R.id.btn_text://文字水印
                tv_wenzi.setTextColor(getResources().getColor(R.color.theme_gold));
                tv_tupian.setTextColor(getResources().getColor(R.color.white));
                initTextStickerView();  //添加文字界面
                startActivityForResult(new Intent(VideoAddWater2Activity.this, SettingTextActivity.class)
                        , REQUEST_CODE_SETTING_TEXT);
                break;
            case R.id.btn_image://图片水印
                tv_wenzi.setTextColor(getResources().getColor(R.color.white));
                tv_tupian.setTextColor(getResources().getColor(R.color.theme_gold));
                initImageStickerView();
                selectFromAblum();  //选择输入图片，点击进入相册
                break;
            case R.id.btn_submit://保存
//                save();
                break;
        }
    }

    private void saveText(String text, String color, int degree, int x, int y, int a) {

    }

    private void saveImage(String text, String color, int degree, int x, int y, int a) {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoAddWater2Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoAddWater2Activity");//统计页面
        MobclickAgent.onPause(this);
    }
}
